/**
 * 日期格式化
 */
Date.prototype.format = function (format) {
  var date = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "q+": Math.floor((this.getMonth() + 3) / 3),
    "S+": this.getMilliseconds()
  };
  if (/(y+)/i.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (var k in date) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1
        ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
    }
  }
  return format;
}
Date.daysInMonth = function (year, month) {
  if (month == 1) {
    if (year % 4 == 0 && year % 100 != 0)
      return 29;
    else
      return 28;
  } else if ((month <= 6 && month % 2 == 0) || (month = 6 && month % 2 == 1))
    return 31;
  else
    return 30;
};
/**
 * 日期与月份相加
 */
Date.prototype.addMonth = function (addMonth) {
  var y = this.getFullYear();
  var m = this.getMonth();
  var nextY = y;
  var nextM = m;
  //如果当前月+要加上的月>11 这里之所以用11是因为 js的月份从0开始
  if ((m + addMonth) > 11) {
    nextY = y + 1;
    nextM = parseInt(m + addMonth) - 12;
  } else {
    nextM = this.getMonth() + addMonth
  }
  var daysInNextMonth = Date.daysInMonth(nextY, nextM);
  var day = this.getDate();
  if (day > daysInNextMonth) {
    day = daysInNextMonth;
  }
  return new Date(nextY, nextM, day);
};
/**
 * 获取格式化的日期
 */
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
/**
 * 获取格式化的时间
 */
const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const isBlank = value => {
  if (!value || value == 0 || value == "")
    return true;
  return false;
}
/**
 * 从本地缓存获取数据
 */
const getStorage = key => {
  var value;
  try {
    value = wx.getStorageSync(key);
  } catch (e) {
  }
  return value;
}
/**
 * 从本地缓存获取数据，并从缓存中删除
 */
const removeStorage = key => {
  var value;
  try {
    value = wx.getStorageSync(key);
  } catch (e) {
  }
  try {
    var param = { "key": key };
    wx.removeStorage(param);
  } catch (e) {
  }
  return value;
}
/**
 * 保存数据到本地缓存
 */
const setStorage = (key, value) => {
  try {
    wx.setStorageSync(key, value)
  } catch (e) { }
}
/**
 * 检测是否登录，并有操作权限
 */
const checkLogin = () => {
  const app = getApp();
  if (!app.isLogin()) {
    wx.showModal({
      title: '操作提示',
      content: '没登录不能操作，是否立即登录？',
      success(res) {
        if (res.confirm) {
          // 没有登录，跳转授权页
          wx.navigateTo({
            url: '/pages/index/login',
          })
        }
      }
    });
    return false;
  }
  return true;
}
/**
 * 刷新token
 */
const reloadToken = (callOptions) => {
  var that = this;
  const app = getApp();
  if (!app.globalData.userData.openid) {
    console.error("未登录，不能操作，openid为空不能刷新token");
    return;
  }
  var params = { openid: app.globalData.userData.openid };
  wx.request({
    url: app.globalData.apiUri + '/app/wx/reloadToken',
    header: {
      'AppType': app.globalData.appType,
      'content-type': 'application/x-www-form-urlencoded'
    },
    data: params,
    method: 'POST',
    success(logRes) {
      var rdata = logRes.data;
      if (rdata.code == 0) {
        var userData = rdata.userData;
        app.globalData.userData = userData;
        try {
          wx.setStorageSync('userData', userData)
          //res.data.msg = "本次请求出问题，请重试";
          callOptions.params.noGetToken = "Y";
          callOptions.call(callOptions.params);
        } catch (e) {
        }
      } else {
        wx.showModal({
          content: rdata.msg,
          showCancel: false
        });
      }
    }
  })
}
/**
 * 每次请求后台的头部数据
 */
function getHeader(app) {
  if(!app)
  {
    app=getApp();
  }
  var token = app.getToken();
  if (!token) {
    return null;
  }
  var merchantId = 0;
  if (app.globalData.userData && app.globalData.userData.merchantId) {
    merchantId = app.globalData.userData.merchantId;
  }

  var headers = { 'AppType': app.globalData.appType };
  headers["token"] = token;
  headers["merchantId"] = merchantId;
  return headers;
}
/**
 * 请求后台，GET
 * options:{uri:"",start:function,success:function,complete:function,fail:function}
 */
const gets = (options) => {
  const app = getApp();
  var headers = getHeader(app);
  if (headers == null) {
    return;
  }
  if (options.start) {
    options.start();
  }
  var getOptions = {
    url: app.globalData.apiUri + options.uri,
    header: headers,
    method: 'GET',
    success(res) {
      try {
        var r = res.data;
        if (r.code == 0) {
          if (options.success) {
            options.success(r);
          }
        } else if (r.code == 3 && !options.noGetToken) {
          reloadToken({ call: gets, params: options });
        } else {
          wx.showModal({
            content: r.msg,
            showCancel: false
          });
        }
      } catch (e) {
        var msg = "";
        if ("string" == typeof e) {
          msg = e;
        } else {
          console.error(e);
          msg = e.message;
        }
        wx.showModal({
          content: msg,
          showCancel: false
        });
      }
    },
    fail: function () {
      if (options.fail) {
        options.fail();
      }
    },
    complete: function () {
      if (options.complete) {
        options.complete();
      }
    }
  };

  if (options.complete) {
    getOptions.complete = options.complete;
  }
  wx.request(getOptions);
}
/**
 * 请求后台，POST
 * options:{uri:"",params:{},start:function,success:function,complete:function,fail:function,contentTypeJson:true}
 */
const post = (options) => {
  const app = getApp();
  if (!options.params) {
    options.params = {};
  }
  var header = options.header;
  if(!header)
    header = getHeader(app);
  if (header == null) {
    return;
  }
  if (options.contentTypeJson){
    header['content-type'] = 'application/json';
  } else if (!header['content-type']) {
    header['content-type'] = 'application/x-www-form-urlencoded';
  } 
  if (options.start) {
    options.start();
  }
  var postOptions = {
    url: app.globalData.apiUri + options.uri,
    header: header,
    data: options.params,
    method: 'POST',
    success(res) {
      try {
        var r = res.data;
        if (r.code == 0) {
          options.success(r);
        } else if (r.code == 3 && !options.noGetToken) {
          reloadToken({ call: post, params: options });
        } else {
          if (options.error) {
            options.error();
          }
          wx.showModal({
            content: r.msg,
            showCancel: false
          });
        }
      } catch (e) {
        if (options.error) {
          options.error();
        }
        var msg;
        if ("string" == typeof e) {
          msg = e;
        } else {
          console.error(e);
          msg = e.message;
        }
        wx.showModal({
          content: msg,
          showCancel: false
        });
      }
    },
    fail: function () {
      if (options.fail) {
        options.fail();
      }
    },
    complete: function () {
      if (options.complete) {
        options.complete();
      }
    }
  };
  wx.request(postOptions);
}
/**
 * 从后台请求数据，POST，并对数据进行分页
 */
const pagingPost = (options) => {
  const app = getApp();
  var header = options.header;
  if (!header)
    header = getHeader(app);
  if (header == null) {
    return;
  }
  if (!header['content-type']) {
    header['content-type'] = 'application/x-www-form-urlencoded';
  }

  if (!options.dataList) {
    console.error("options.dataList不能为空");
    return;
  }
  var thatPage;
  if (options.thatPage == undefined) {
    var pages = getCurrentPages();
    thatPage = pages[pages.length - 1];
  } else {
    thatPage = options.thatPage;
  }

  if (thatPage.data.paging == undefined) {
    console.error("data.paging不能为空");
    return;
  }
  if (options.params.page == undefined) {
    options.params.page = thatPage.data.paging.page;
  }
  if (options.params.limit == undefined) {
    options.params.limit = thatPage.data.paging.limit;
  }
  wx.showLoading({
    title: '加载中',
    icon: 'loading',
  });
  var postOptions = {
    url: app.globalData.apiUri + options.uri,
    header: header,
    data: options.params,
    method: 'POST',
    success(res) {
      try {
        var r = res.data;
        if (r.code == 0) {
          var tdata = { "paging.totalPage": r.page.totalPage, "paging.page": r.page.currPage };
          if (r.page.currPage == 1) {
            tdata[options.dataList] = r.page.list;
          } else {
            var list = thatPage.data[options.dataList].concat(r.page.list);
            tdata[options.dataList] = list;
          }
          thatPage.setData(tdata);
          if (options.success) {
            options.success(r);
          }
        } else if (r.code == 3 && !options.noGetToken) {
          reloadToken({ call: pagingPost, params: options });
        } else {
          wx.showModal({
            content: r.msg,
            showCancel: false
          });
        }
      } catch (e) {
        var msg;
        if ("string" == typeof e) {
          msg = e;
        } else {
          console.error(e);
          msg = e.message;
        }
        wx.showModal({
          content: msg,
          showCancel: false
        });
      }
    },
    complete: function () {
      wx.hideLoading();
    }
  };
  wx.request(postOptions);
}
/**
 * 下一页数据请求
 */
const nextPage = (call, thatPage) => {
  if (thatPage == undefined) {
    var pages = getCurrentPages();
    thatPage = pages[pages.length - 1];
  }

  if (thatPage.data.paging == undefined) {
    console.error("data.paging不能为空");
    return;
  }
  var page = thatPage.data.paging.page + 1;
  if (page > thatPage.data.paging.totalPage) {
    return;
  }
  var param = { "page": page, "limit": thatPage.data.paging.limit };
  call(param);
}
/**
 * 设置错误提示信息
 */
const showTopTips = warnMsg => {
  var pages = getCurrentPages();
  var thatPage = pages[pages.length - 1];
  thatPage.setData({
    showTopTips: true,
    topTipTxt: warnMsg
  });
  setTimeout(function () {
    thatPage.setData({
      showTopTips: false,
      topTipTxt: ""
    });
  }, 2000);
}

module.exports = {
  formatTime: formatTime,
  formatDate: formatDate,
  isBlank: isBlank,
  getStorage: getStorage,
  setStorage: setStorage,
  removeStorage: removeStorage,
  checkLogin: checkLogin,
  gets: gets,
  post: post,
  pagingPost: pagingPost,
  nextPage: nextPage,
  getHeader: getHeader,
  showTopTips: showTopTips
}